/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.delivery.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yami.shop.bean.app.dto.DeliveryDto;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.model.Delivery;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.model.OrderSelfStation;
import com.yami.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.comment.param.DvyOrderParam;
import com.yami.shop.delivery.comment.param.OrderParam;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.delivery.comment.service.OrderSelfStationService;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lhd on 2020/05/15.
 */
@Controller
@AllArgsConstructor
@RequestMapping("/platform/orderDelivery")
public class OrderDeliveryController {

    private final OrderService orderService;
    private final UserAddrOrderService userAddrOrderService;
    private final OrderItemService orderItemService;

    private final DeliveryOrderService deliveryOrderService;

    private final DeliveryService deliveryService;

    private final MapperFacade mapperFacade;

    private final OrderSelfStationService orderSelfStationService;

    /**
     * 查询订单物流包裹信息
     */
    @PutMapping("/getOrderDeliveries/{orderNumber}")
    public ResponseEntity<List<DeliveryOrder>> getOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.listDetailDelivery(orderNumber);
        return ResponseEntity.ok(deliveryOrders);
    }


    /**
     * 修改订单物流包裹信息
     */
    @PutMapping("/updateOrderDeliveries")
    public ResponseEntity<Void> updateOrderDeliveries(@RequestBody DvyOrderParam dvyOrderParam) {
        List<DeliveryOrder> deliveryOrders = dvyOrderParam.getDeliveryOrders();
        deliveryOrderService.updateOrderDeliveries(deliveryOrders);
        return ResponseEntity.ok().build();
    }

    /**
     * 订单项分包裹发货
     */
    @PutMapping("/orderItemsDelivery")
    public ResponseEntity<Void> orderItemsDelivery(@RequestBody DeliveryOrderItemParam deliveryOrderParam) {
        deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam);
        return ResponseEntity.ok().build();
    }

    /**
     * 订单项待发货数量查询
     */
    @GetMapping("/getOrderItemUnDelivery/{orderNumber}")
    public ResponseEntity<Order> getOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderNumber, orderNumber).eq(OrderItem::getShopId, shopId));
        if(CollectionUtils.isEmpty(orderItems)){
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Map<Long,Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())){
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ?orderItem.getProdCount():orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))){
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            }else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))){
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
        }
        order.setOrderItems(orderItems);
        return ResponseEntity.ok(order);
    }


    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
    public ResponseEntity<OrderParam> info(@PathVariable("orderNumber") String orderNumber) {
        Order order = orderService.getOrderDetailByOrderNumberAndShopId(orderNumber,null, I18nMessage.getDbLang());
        if (Objects.nonNull(order.getDvyType()) && order.getDvyType().equals(DvyType.STATION.value())){
            OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, order.getOrderNumber()));
            order.getUserAddrOrder().setMobile(orderSelfStation.getStationUserMobile());
            order.getUserAddrOrder().setReceiver(orderSelfStation.getStationUserName());
        }
        OrderParam orderParam = mapperFacade.map(order, OrderParam.class);
        orderParam.setScore(orderParam.getOrderItems().stream().mapToInt(OrderItem::getUseScore).sum());
        //查询包裹信息
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.getAndDeliveryItemInfo(orderNumber);
        // 查询物流详情信息
        // 物流公司名称、官网、订单号、物流详情信息
        try {
            for (DeliveryOrder deliveryOrder : deliveryOrders) {
                // 查询交易单
                Delivery delivery = deliveryService.getById(deliveryOrder.getDvyId());
                DeliveryDto deliveryDto;
                // 解析的物流详情明细
                String detail = deliveryService.query(delivery.getDvyId(), deliveryOrder.getDvyFlowId());
                deliveryDto = new Gson().fromJson(detail, DeliveryDto.class);
                deliveryDto.setDvyFlowId(deliveryOrder.getDvyFlowId());
                deliveryDto.setCompanyName(delivery.getDvyName());
                deliveryDto.setCompanyHomeUrl(delivery.getCompanyHomeUrl());
                deliveryOrder.setDeliveryDto(deliveryDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 查询出错
            throw new YamiShopBindException("yami.query.error");
        }
        orderParam.setDeliveryExpresses(deliveryOrders);
        return ResponseEntity.ok(orderParam);
    }

}
